import React from 'react';
import { ajax, api } from '../../config.service';
import { Table, Col, Button, Tabs, Modal, Form, Input, Icon, Popconfirm, message, DatePicker } from 'antd';

const Component = React.Component;
const FormItem = Form.Item;

/**
 * 基本属性
 * url:数据加载的URL
 * requestData:要请求的数据
 * path:JSON数据的PATH
 * translate:翻译Object
 * operators:操作数组，将数据推送到接口，格式是:[{url:"推送目标URL",fun:"操作函数，和前一个参数只能二选一，参数是第一个是组件，第二个是response",callback:"当是url时，调用成功时交给此函数处理","title":"操作标题"},]
 */
class AjaxListTable extends Component {

    constructor(props) {
        super(props);
        this.state = {
            content: <div>没有数据</div>
        };
    }

    componentDidMount() {
        this.load();
    }

    load() {
        let me = this;
        ajax.postJson(this.props.url, this.props.reqeustData ? this.props.reqeustData : {}, (response) => {
            let operators = me.props.operators;
            let translate = me.props.translate;
            let exclude = me.props.exclude;

            if (operators && operators.length) {
                for (let i = 0; i < operators.length; i++) {
                    let operator = operators[i];
                    if (operator.url) {
                        operators[i] = {
                            fun: (record) => {
                                ajax.postJson(operator.url, record, (resp) => {
                                    operator.callback(me, resp);
                                });
                            },
                            title: operator.title
                        };
                    }
                }
            }
            //后期考虑使用网络translate
            me.setState({
                content: <ListTable data={response} path="data" translate={translate} operators={operators} exclude={exclude} />
            });
        });
    }

    render() {
        return (<div>{this.state.content}</div>);
    }

}

/**
 * 参数
 * data:数据
 * path:路径
 * exclude:["id"]//排除显示的字段
 * translate:翻译
 * operators:[{fun,title}]
 */
class ListTable extends Component {

    constructor(props) {
        super(props);
        this.state = {
            content: <div>没有数据</div>
        };
    }

    componentDidMount() {
        this.refresh(this.props);
    }

    refresh(props) {

        let me = this;
        let paths = props.path ? props.path.split("\\.") : [];
        let current = props.data ? props.data : [];
        let translate = props.translate ? props.translate : {};
        let operators = props.operators ? props.operators : [];
        let exclude = props.exclude ? props.exclude : [];

        for (let i = 0; i < paths.length; i++) {
            current = current[paths[i]];
        }
        if (current && current.length && current.length > 0) {
            let metaDataSample = current[0];
            let columns = [];
            for (let key in translate) {
                let show = true;
                for (let excludeId = 0; excludeId < exclude.length; excludeId++) {
                    show = show && exclude[excludeId] != key;
                }
                if (show) {
                    let value = metaDataSample[key];
                    if (typeof (value) == 'string' || typeof (value) == 'number') {
                        columns.push({ title: translate[key], dataIndex: key, key: key });
                    } else {
                    }
                }
            }
            for (let key in metaDataSample) {
                let show = true;
                for (let excludeId = 0; excludeId < exclude.length; excludeId++) {
                    show = show && exclude[excludeId] != key;
                }
                if (show) {
                    if (!translate[key] || translate[key] == 0 || translate[key] == false) {
                        let value = metaDataSample[key];
                        if (typeof (value) == 'string' || typeof (value) == 'number') {
                            console.log(key, value);
                            columns.push({ title: key, dataIndex: key, key: key });
                        } else {
                            console.log(key, typeof (value));
                        }
                    }
                }
            }
            if (operators && operators.length) {
                columns.push({
                    title: '操作',
                    key: 'action',
                    render: (text, record) => {
                        let opers = [];
                        for (let i = 0; i < operators.length; i++) {
                            let operator = operators[i];
                            if (opers.length > 0) {
                                opers.push(<span>&nbsp;</span>)
                            }
                            opers.push(<a href="#" onClick={() => { operator.fun(record); }}>{operator.title}</a>)
                        }
                        return (
                            <span>
                                {opers}
                            </span>
                        )
                    }
                });
            }
            let table = [];
            table.push(<Table pagination={false} dataSource={current} columns={columns}></Table>);
            me.setState({
                content: table
            });
        } else {
            this.setState({
                content: <div>没有数据</div>
            });
        }
    }

    render() {
        return (<div>{this.state.content}</div>);
    }

}

class FormWrapper extends Component {

    constructor(props) {
        super(props);
        if (props.createCallback) {
            props.createCallback(this);
        }
    }

    setFieldsValue(values){
        this.formRef.props.form.setFieldsValue(values);
    }

    getFieldsValue(){
        return this.formRef.props.form.getFieldsValue();
    }

    getFieldValues() {
        return this.formRef.props.form.getFieldsValue();
    }

    componentWillReceiveProps(props) {
    }

    componentDidUpdate() {
    }

    render() {
        const DForm = Form.create({})(DataForm);
        let me = this;
        return <DForm values={this.props.values} createCallback={(form) => { me.formRef = form; }} items={this.props.items} />
    }
}

class DataForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
            items: props.items ? props.items : []
        };
        props.createCallback(this);
    }

    componentDidMount() {
        this.props.form.setFieldsValue(this.props.values);
    }

    componentDidUpdate() {

    }

    componentWillReceiveProps(props) {
    }

    render() {
        let items = [];
        const { getFieldDecorator } = this.props.form;
        for (let i = 0; i < this.state.items.length; i++) {
            let item = this.state.items[i];
            if (item.type && item.type == 'date') {
                items.push(<FormItem label={item.name}>
                    {getFieldDecorator(item.key, {
                        rules: [{ ...(item.props ? item.props : {}) }],
                    })(
                        <DatePicker showTime format={item.format ? item.format : "YYYY-MM-DD"} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder={item.name} />
                    )}
                </FormItem>);
            } else {
                items.push(<FormItem label={item.name}>
                    {getFieldDecorator(item.key, {
                        rules: [{ ...(item.props ? item.props : {}) }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder={item.name} />
                    )}
                </FormItem>);
            }
        }
        return (
            <Form>
                {items}
            </Form>
        );
    }
}

export { AjaxListTable, ListTable, DataForm, FormWrapper }